/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.user.rest;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.logging.aop.log.AppLog;
import co.yixiang.common.aop.NoRepeatSubmit;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.interceptor.AuthCheck;
import co.yixiang.constant.ShopConstants;
import co.yixiang.enums.BillInfoEnum;
import co.yixiang.modules.order.service.YxStoreOrderService;
import co.yixiang.modules.order.vo.UserOrderCountVo;
import co.yixiang.modules.product.domain.YxStoreProductRelation;
import co.yixiang.modules.product.service.YxStoreProductRelationService;
import co.yixiang.modules.product.vo.YxStoreProductRelationQueryVo;
import co.yixiang.modules.shop.domain.YxSystemUserLevel;
import co.yixiang.modules.shop.rest.CommissionMainController;
import co.yixiang.modules.shop.rest.TDMQMessageController;
import co.yixiang.modules.shop.service.YxSystemAttachmentService;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import co.yixiang.modules.shop.service.YxSystemGroupDataService;
import co.yixiang.modules.user.domain.MonthlyManagementAward;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.param.UserEditParam;
import co.yixiang.modules.user.service.*;
import co.yixiang.modules.user.vo.MonthlyAwardDetailVo;
import co.yixiang.modules.user.vo.MonthlyAwardVo;
import co.yixiang.modules.user.vo.SignVo;
import co.yixiang.modules.user.vo.YxUserQueryVo;
import co.yixiang.utils.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

import static co.yixiang.constant.SystemConfigConstants.YSHOP_SHOW_RECHARGE;

/**
 * <p>
 * 用户控制器
 * </p>
 *
 * @author hupeng
 * @since 2019-10-16
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "用户中心", tags = "用户:用户中心", description = "用户中心")
public class UserController {

    private final YxUserService yxUserService;
    private final YxSystemGroupDataService systemGroupDataService;
    private final YxStoreOrderService orderService;
    private final YxStoreProductRelationService relationService;
    private final YxUserSignService userSignService;
    private final YxUserBillService userBillService;
    private final MonthlyManagementAwardService monthlyManagementAwardService;
    private final MonthlyManagementAwardDetailService monthlyManagementAwardDetailService;
    private final YxSystemConfigService systemConfigService;
    private final co.yixiang.modules.shop.rest.TDMQMessageController TDMQMessageController;
    private final co.yixiang.modules.shop.rest.CommissionNewController CommissionNewController;
    private final YxSystemUserLevelService yxSystemUserLevelService;
    private final YxSystemAttachmentService systemAttachmentService;
    private final RedisUtils redisUtil;


    /**
     * 用户资料
     */
    @AuthCheck
    @GetMapping("/userinfo")
    @ApiOperation(value = "获取用户信息",notes = "获取用户信息",response = YxUserQueryVo.class)
    public ApiResult<Object> userInfo(){
        YxUser yxUser = LocalUser.getUser();
        return ApiResult.ok(yxUserService.getNewYxUserById(yxUser));
    }

    /**
     * 获取系统时间
     */
    @GetMapping("/getCurrentDate")
    @ApiOperation(value = "获取系统时间",notes = "获取系统时间")
    public ApiResult<Object> getCurrentDate(){
        Date sysDate = new Date();
        return ApiResult.ok(sysDate);
    }

    /**
     * 获取导航图
     */
    @GetMapping("/getNavigationPic")
    @ApiOperation(value = "获取导航图",notes = "获取导航图")
    public ApiResult<Object> getNavigationPic(){
        String loadIndexImg =systemConfigService.getData(ShopConstants.LOAD_INDEX_IMG);
        return ApiResult.ok(loadIndexImg);
    }

    /**
     * 获取关于图
     */
    @GetMapping("/getAboutImages")
    @ApiOperation(value = "获取关于图",notes = "获取关于图")
    public ApiResult<Object> getAboutImages(){
        String aboutImages =systemConfigService.getData(ShopConstants.ABOUT_IMAGES);
        if(ObjectUtil.isNotNull(LocalUser.getUser())) {
            log.info("关于====");
            long uid = LocalUser.getUser().getUid();
            log.info("uid====" + uid);
            //添加足迹
            YxStoreProductRelation storeProductRelation = new YxStoreProductRelation();
            storeProductRelation.setProductId(new Long(1));
            storeProductRelation.setUid(uid);
            storeProductRelation.setCategory("关于");
            storeProductRelation.setCreateTime(new Date());
            storeProductRelation.setType("foot");
            relationService.save(storeProductRelation);
        }
        return ApiResult.ok(aboutImages);
    }

    /**
     * 用户上级为空时,扫码更新上级
     */
    @AuthCheck
    @GetMapping("/updateSpread/{spread}")
    @ApiOperation(value = "更新上级",notes = "更新上级",response = YxUserQueryVo.class)
    public ApiResult<Object> updateSpread(@PathVariable String spread){
        log.info("spread==ttttt==="+spread);
        YxUser yxUser = LocalUser.getUser();
        log.info("Uid==="+yxUser.getUid());
        yxUser =yxUserService.getById(yxUser.getUid());
        log.info("IsNoSpread==="+yxUser.getIsNoSpread());
        if(!"Y".equals(yxUser.getIsNoSpread())){
            yxUserService.setSpread(spread, yxUser.getUid());
            yxUser =yxUserService.getById(yxUser.getUid());
            //yxUser.setSpreadUid(Long.parseLong(spread));
            //yxUser.setSpreadTime(new Date());
            yxUserService.updateById(yxUser);
            if(yxUser.getSpreadUid().intValue() !=0){
                yxUserService.initPath(yxUser.getUid(),spread);
                //TDMQMessageController.tdmqMessage("user_id:"+yxUser.getUid().toString());
            }
        }
        yxUser =yxUserService.getById(yxUser.getUid());
        return ApiResult.ok(yxUserService.getNewYxUserById(yxUser));
    }

    /**
     * 手机号查询用户
     */
    @AuthCheck
    @GetMapping("/queryUser4mobile/{phone}")
    @ApiOperation(value = "手机号查询用户",notes = "手机号查询用户",response = YxUserQueryVo.class)
    public ApiResult<Object> queryUser4mobile(@PathVariable String phone){
        log.info("phone==ttttt==="+phone);
        YxUser yxUser = yxUserService.getOne(Wrappers.<YxUser>lambdaQuery()
                .eq(YxUser::getPhone,phone),false);
        if(yxUser == null) {
            throw new YshopException("手机号码不正确");
        }
        return ApiResult.ok(yxUserService.getNewYxUserById(yxUser));
    }

    /**
     * 验证交易密码
     */
    @AuthCheck
    @GetMapping("/traderPwd/{password}/{uid}/{traderSum}")
    @Synchronized
    @ApiOperation(value = "验证交易密码",notes = "验证交易密码",response = YxUserQueryVo.class)
    public  ApiResult<String> traderPwd(@PathVariable String password,@PathVariable String uid,@PathVariable String traderSum){
        log.info("phone==ttttt==="+password);
        String s =SecureUtil.md5(password);
        YxUser fromUser = LocalUser.getUser();
        YxUser toUser =yxUserService.getById(Long.parseLong(uid));
        if(!s.equals(fromUser.getWechatAccount())) {
            return ApiResult.fail("交易密码错误");
        }else{
            BigDecimal tSum =new BigDecimal(traderSum);
            CommissionNewController.traderMoney(fromUser,toUser,tSum);
            return ApiResult.ok("","交易成功");
        }
    }

    /**
     * 获取个人中心菜单
     */
    @GetMapping("/menu/user")
    @ApiOperation(value = "获取个人中心菜单",notes = "获取个人中心菜单")
    public ApiResult<Map<String,Object>> userMenu(){
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("routine_my_menus",systemGroupDataService.getDatas(ShopConstants.YSHOP_MY_MENUES));
        return ApiResult.ok(map);
    }



    /**
     * 订单统计数据
     */
    @AppLog(value = "查看订单统计数据", type = 1)
    @AuthCheck
    @GetMapping("/order/data")
    @ApiOperation(value = "订单统计数据",notes = "订单统计数据")
    public ApiResult<UserOrderCountVo> orderData(){
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(orderService.orderData(uid));
    }

    /**
     * 获取收藏产品
     */
    @AuthCheck
    @GetMapping("/collect/user")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码,默认为1", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "页大小,默认为10", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "type", value = "foot为足迹,collect为收藏", paramType = "query", dataType = "String")
    })
    @ApiOperation(value = "获取收藏产品,或足迹",notes = "获取收藏产品,或足迹")
    public ApiResult<List<YxStoreProductRelationQueryVo>> collectUser(@RequestParam(value = "page",defaultValue = "1") int page,
                                                                      @RequestParam(value = "limit",defaultValue = "10") int limit,
                                                                      @RequestParam(value = "type") String type){
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(relationService.userCollectProduct(page,limit,uid,type));
    }

    /**
     * 获取收藏产品
     */
    @AuthCheck
    @GetMapping("/collect/user4product")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码,默认为1", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "页大小,默认为10", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "type", value = "foot为足迹,collect为收藏", paramType = "query", dataType = "String")
    })
    @ApiOperation(value = "获取收藏产品,或足迹",notes = "获取收藏产品,或足迹")
    public ApiResult<List<YxStoreProductRelationQueryVo>> collectUser4product(@RequestParam(value = "page",defaultValue = "1") int page,
                                                                      @RequestParam(value = "limit",defaultValue = "10") int limit,
                                                                      @RequestParam(value = "type") String type,
                                                                              @RequestParam(value = "uid") String uid){
        //Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(relationService.userCollectProduct(page,limit,Long.valueOf(uid),type));
    }

    /**
     * 获取所有直属足迹信息
     */
    @AuthCheck
    @GetMapping("/collect/user4all")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码,默认为1", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "页大小,默认为10", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "type", value = "foot为足迹,collect为收藏", paramType = "query", dataType = "String")
    })
    @ApiOperation(value = "获取收藏产品,或足迹",notes = "获取收藏产品,或足迹")
    public ApiResult<List<YxStoreProductRelationQueryVo>> collectUser4all(@RequestParam(value = "page",defaultValue = "1") int page,
                                                                              @RequestParam(value = "limit",defaultValue = "10") int limit,
                                                                              @RequestParam(value = "type") String type){
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(relationService.userCollectAll(page,limit,Long.valueOf(uid),type,3));
    }

    /**
     * 用户资金统计
     */
    @AppLog(value = "查看用户资金统计", type = 1)
    @AuthCheck
    @GetMapping("/user/balance")
    @ApiOperation(value = "用户资金统计",notes = "用户资金统计")
    public ApiResult<Object> userBalance(){
        YxUser yxUser = LocalUser.getUser();
        Map<String,Object> map = Maps.newHashMap();
        Double[] userMoneys = yxUserService.getUserMoney(yxUser.getUid());
        map.put("now_money",yxUser.getNowMoney());
        map.put("orderStatusSum",userMoneys[0]);
        map.put("recharge",userMoneys[1]);
        map.put("is_hide",systemConfigService.getData(YSHOP_SHOW_RECHARGE));
        return ApiResult.ok(map);
    }


    /**
     * 签到用户信息
     */
    @AppLog(value = "签到用户信息", type = 1)
    @AuthCheck
    @PostMapping("/sign/user")
    @ApiOperation(value = "签到用户信息",notes = "签到用户信息")
    public ApiResult<YxUserQueryVo> sign(){
        YxUser yxUser = LocalUser.getUser();
        return ApiResult.ok(userSignService.userSignInfo(yxUser));
    }

    /**
     * 签到配置
     */
    @GetMapping("/sign/config")
    @ApiOperation(value = "签到配置",notes = "签到配置")
    public ApiResult<Object> signConfig(){
        return ApiResult.ok(systemGroupDataService.getDatas(ShopConstants.YSHOP_SIGN_DAY_NUM));
    }

    /**
     * 签到列表
     */
    @AppLog(value = "查看签到列表", type = 1)
    @AuthCheck
    @GetMapping("/sign/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码,默认为1", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "页大小,默认为10", paramType = "query", dataType = "int")
    })
    @ApiOperation(value = "签到列表",notes = "签到列表")
    public ApiResult<List<SignVo>> signList(@RequestParam(value = "page",defaultValue = "1") int page,
                                            @RequestParam(value = "limit",defaultValue = "10") int limit){
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(userSignService.getSignList(uid,page,limit));
    }

    /**
     * 签到列表（年月）
     */

    @AuthCheck
    @GetMapping("/sign/month")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码,默认为1", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "页大小,默认为10", paramType = "query", dataType = "int")
    })
    @ApiOperation(value = "签到列表（年月）",notes = "签到列表（年月）")
    public ApiResult<Object> signMonthList(@RequestParam(value = "page",defaultValue = "1") int page,
                                           @RequestParam(value = "limit",defaultValue = "10") int limit){
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(userBillService.getUserBillList(page, limit,uid, BillInfoEnum.SIGN_INTEGRAL.getValue()));
    }

    /**
     * 开始签到
     */
    @AppLog(value = "开始签到", type = 1)
    @NoRepeatSubmit
    @AuthCheck
    @PostMapping("/sign/integral")
    @ApiOperation(value = "开始签到",notes = "开始签到")
    public ApiResult<Object> signIntegral(){
        YxUser yxUser = LocalUser.getUser();
        int integral = userSignService.sign(yxUser);;

        Map<String,Object> map = new LinkedHashMap<>();
        map.put("integral",integral);
        return ApiResult.ok(map,"签到获得" + integral + "积分");
    }

    @AppLog(value = "用户修改信息", type = 1)
    @AuthCheck
    @PostMapping("/user/edit")
    @ApiOperation(value = "用户修改信息",notes = "用修改信息")
    public ApiResult<Object> edit(@Validated @RequestBody UserEditParam param){
        YxUser yxUser = LocalUser.getUser();
        yxUser.setAvatar(param.getAvatar());
        yxUser.setNickname(param.getNickname());
        yxUser.setWechatAccount(param.getWechatAccount());
        yxUser.setBankCode(param.getBankCode());
        yxUser.setBankUserName(param.getBankUserName());
        yxUser.setBankName(param.getBankName());
        yxUser.setCardId(param.getCardId());
        yxUserService.updateById(yxUser);
        if(ObjectUtil.isNotEmpty(param.getAvatar())){
            systemAttachmentService.attachmentByUidDelete("2",new Long(0),yxUser.getUid());
        }
        return ApiResult.ok("修改成功");
    }

    @AppLog(value = "用户修改交易密码信息", type = 1)
    @AuthCheck
    @PostMapping("/user/updatePassword/{password}/{code}")
    @ApiOperation(value = "用户修改信息",notes = "用修改信息")
    public ApiResult<String> updatePassword(@Validated @PathVariable String password,@PathVariable String code){
        YxUser yxUser = LocalUser.getUser();
        String codeKey = "code_" + yxUser.getPhone();
        if (ObjectUtil.isNotNull(redisUtil.get(codeKey))) {
            if(code.equals(redisUtil.get(codeKey))){
                yxUser.setWechatAccount(SecureUtil.md5(password));
                yxUserService.updateById(yxUser);
                return ApiResult.ok("修改成功");
            }else{
                return ApiResult.fail("验证码不正确!");
            }
        }else{
            return ApiResult.fail("验证码已失效!");
        }

    }

    /**
     * 联创查询列表
     * @return mixed
     */
    @AppLog(value = "联创查询列表", type = 1)
    @AuthCheck
    @GetMapping("/monthAward/{month}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码,默认为1", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "页大小,默认为10", paramType = "query", dataType = "int"),
    })
    @ApiOperation(value = "联创查询列表",notes = "联创查询列表")
    public ApiResult<Object> monthAward(@RequestParam(value = "page",defaultValue = "1") int page,
                                                  @RequestParam(value = "limit",defaultValue = "10") int limit,
                                                  @PathVariable String month){
        Long uid = LocalUser.getUser().getUid();
        //month ="2022-03";
        MonthlyManagementAward mma = monthlyManagementAwardService.getOne(Wrappers.<MonthlyManagementAward>lambdaQuery()
                .eq(MonthlyManagementAward::getMonth, month)
                .eq(MonthlyManagementAward::getUid, uid));
        //BigDecimal totalSum =BigDecimal.ZERO;
        //BigDecimal receiptsSum =BigDecimal.ZERO;
        MonthlyAwardVo vo =new MonthlyAwardVo();
        if (ObjectUtil.isNotNull(mma)) {
            vo.setUid(mma.getUid());
            vo.setLevel(mma.getLevel());
            vo.setNickname(mma.getNickname());
            vo.setUserPhone(mma.getUserPhone());
            vo.setHeadimgurl(mma.getHeadimgurl());
            vo.setTotalSum(mma.getTotalSum());
            vo.setReceivableSum(mma.getReceivableSum());
            vo.setReceiptsSum(mma.getReceiptsSum());
            List<MonthlyManagementAward> childList = monthlyManagementAwardService.list(Wrappers.<MonthlyManagementAward>lambdaQuery()
                    .eq(MonthlyManagementAward::getMonth, month)
                    .eq(MonthlyManagementAward::getParentId, mma.getUid()));
            List<MonthlyAwardDetailVo> detailList =new ArrayList<MonthlyAwardDetailVo>();
            if(childList.size()>0){
                for(int i=0;i<childList.size();i++){
                    MonthlyManagementAward child =childList.get(i);
                    MonthlyAwardDetailVo detail =new MonthlyAwardDetailVo();
                    detail.setUid(child.getUid());
                    detail.setLevel(child.getLevel());
                    detail.setNickname(child.getNickname());
                    detail.setHeadimgurl(child.getHeadimgurl());
                    detail.setReceiptsSum(child.getReceiptsSum());
                    detail.setReceivableSum(child.getReceivableSum());
                    detail.setTotalSum(child.getTotalSum());
                    detail.setUserPhone(child.getUserPhone());
                    detailList.add(detail);
                }
            }
            vo.setDetailList(detailList);
        }else{
            vo =monthlyManagementAwardDetailService.getAwardMain4monthList(page,limit,uid,month);
        }
        Map<String,Object> map = new LinkedHashMap<>();
        //List<MonthlyManagementAward> awardList =monthlyManagementAwardService.getManagementAward4monthList(page,limit,uid,month);
        map.put("awardData",vo);
        return ApiResult.ok(map);
    }

    /**
     * 用户级别晋升条件查询
     */
    @AuthCheck
    @GetMapping("/queryUser4Promotion")
    @ApiOperation(value = "用户级别晋升条件查询",notes = "用户级别晋升条件查询",response = YxUserQueryVo.class)
    public ApiResult<Object> queryUser4Promotion(){
        Long uid = LocalUser.getUser().getUid();
        YxUser yxUser = yxUserService.getById(uid);
        String childCount = yxUserService.getChildrens4Main(uid,yxUser.getLevel());//获取当前用户的同级直属人数
        Map<String,Object> map = new LinkedHashMap<>();
        if(Integer.parseInt(childCount)>=3){
            map.put("isSatisfiedPeoper","Y");
        }else{
            map.put("isSatisfiedPeoper","N");
        }
        if(yxUser.getLevel() ==3){
            if(yxUser.getVipCount()>=400){
                map.put("isPromotion","Y");
            }else{
                map.put("isPromotion","N");
            }
        }else if(yxUser.getLevel() ==4){
            if(yxUser.getVipCount()>=2000){
                map.put("isPromotion","Y");
            }else{
                map.put("isPromotion","N");
            }
        }
        return ApiResult.ok(map);
    }

    /**
     * 上级开通直通车授权用户级别
     */
    @AuthCheck
    @GetMapping("/authChildLevel/{uid}/{level}")
    @ApiOperation(value = "上级开通直通车授权用户级别",notes = "上级开通直通车授权用户级别",response = YxUserQueryVo.class)
    public ApiResult<Object> authChildLevel(@PathVariable String uid,@PathVariable String level){
        Long MainUid = LocalUser.getUser().getUid();
        YxUser yxUser = yxUserService.getById(MainUid);
        YxUser childUser = yxUserService.getById(uid);
        Integer userLevel =Integer.valueOf(level);
        Map<String,Object> map = new LinkedHashMap<>();
        YxSystemUserLevel yxSystemUserLevel = yxSystemUserLevelService.getOne(new LambdaQueryWrapper<YxSystemUserLevel>()
                .eq(YxSystemUserLevel::getGrade,childUser.getLevel()));
        if(userLevel==1){
            if(childUser.getLevel()<2) {
                if (yxUser.getVipHroughTrain() > 0) {
                    Integer vipHroughTrain = yxUser.getVipHroughTrain() - 1;
                    Integer authThroughCount = yxUser.getAuthThroughCount() + 1;
                    yxUser.setAuthThroughCount(authThroughCount);
                    yxUser.setVipHroughTrain(vipHroughTrain);
                    childUser.setLevel(2);
                    childUser.setWhetherVipSlim("Y");
                    //childUser.setIsOpenLian("Y");
                    childUser.setVipDate(new Date());
                    childUser.setThroughUid(MainUid);
                    childUser.setAuthDate(new Date());
                    childUser.setAuthRemark("原等级:" + yxSystemUserLevel.getName() + " 调整为店主 ");
                    yxUserService.updateById(yxUser);
                    yxUserService.updateById(childUser);
                    map.put("result", "授权成功!");
                } else {
                    map.put("result", "可授权店主名额不足!");
                }
            }else{
                map.put("result", "直属等级已大于等于店主,无需授权!");
            }
        }else if(userLevel==2){
            if(childUser.getLevel()<2) {
                if(yxUser.getGoldHroughTrain()>0){
                    Integer goldHroughTrain =yxUser.getGoldHroughTrain()-1;
                    Integer authThroughCount =yxUser.getAuthThroughCount()+1;
                    yxUser.setAuthThroughCount(authThroughCount);
                    yxUser.setGoldHroughTrain(goldHroughTrain);
                    childUser.setLevel(userLevel);
                    childUser.setWhetherVipSlim("Y");
                    childUser.setIsOpenLian("Y");
                    childUser.setVipDate(new Date());
                    childUser.setThroughUid(MainUid);
                    childUser.setAuthDate(new Date());
                    childUser.setAuthRemark("原等级:"+yxSystemUserLevel.getName()+" 调整为新媒体导师 ");
                    yxUserService.updateById(yxUser);
                    yxUserService.updateById(childUser);
                    map.put("result","授权成功!");
                }else{
                    map.put("result","可授权新媒体导师名额不足!");
                }
            }else{
                map.put("result", "直属等级已大于等于店主,无需授权!");
            }
        }else if(userLevel==3){
            if(childUser.getLevel()<3) {
                if (yxUser.getDiamondsHroughTrain() > 0) {
                    Integer diamondsHroughTrain = yxUser.getDiamondsHroughTrain() - 1;
                    Integer authThroughCount = yxUser.getAuthThroughCount() + 1;
                    yxUser.setAuthThroughCount(authThroughCount);
                    yxUser.setDiamondsHroughTrain(diamondsHroughTrain);
                    childUser.setLevel(userLevel);
                    childUser.setWhetherVipSlim("Y");
                    childUser.setIsOpenLian("Y");
                    childUser.setVipDate(new Date());
                    childUser.setThroughUid(MainUid);
                    childUser.setAuthDate(new Date());
                    childUser.setAuthRemark("原等级:" + yxSystemUserLevel.getName() + " 调整为新媒体运营师 ");
                    yxUserService.updateById(yxUser);
                    yxUserService.updateById(childUser);
                    map.put("result", "授权成功!");
                } else {
                    map.put("result", "可授权新媒体运营师名额不足!");
                }
            }else{
                map.put("result", "直属等级已大于等于合伙人,无需授权!");
            }
        }

        return ApiResult.ok(map);
    }

    /**
     * uid查找用户
     */
    @AuthCheck
    @GetMapping("/queryUser/{uid}")
    @ApiOperation(value = "uid查找用户",notes = "uid查找用户",response = YxUserQueryVo.class)
    public ApiResult<Object> queryUser(@PathVariable String uid){
        YxUser yxUser = yxUserService.getById(Long.valueOf(uid));
        if(yxUser == null) {
            throw new YshopException("没有查找到用户");
        }
        return ApiResult.ok(yxUserService.getNewYxUserById(yxUser));
    }

    /**
     * uid查找用户
     */
    @GetMapping("/getSystemConfigData")
    @ApiOperation(value = "获取系统参数",notes = "获取系统参数")
    public ApiResult<Object> getSystemConfigData(){
        Map<String,Object> map = new LinkedHashMap<>();
        String indexTopImages =systemConfigService.getData(ShopConstants.INDEX_TOP_IMAGES);
        String userTopImages =systemConfigService.getData(ShopConstants.USER_TOP_IMAGES);
        String userOrderUnpaidImg =systemConfigService.getData(ShopConstants.USER_ORDER_UNPAID_IMG);
        String userOrderPaidImg =systemConfigService.getData(ShopConstants.USER_ORDER_PAID_IMG);
        String userOrderShippedImg =systemConfigService.getData(ShopConstants.USER_ORDER_SHIPPED_IMG);
        String userQrcodeImg =systemConfigService.getData(ShopConstants.USER_QRCODE_IMG);
        String userBottomLogo =systemConfigService.getData(ShopConstants.USER_BOTTOM_LOGO);
        String forceBindMobile =systemConfigService.getData(ShopConstants.FORCE_BIND_MOBILE);
        String isPlaceOrder =systemConfigService.getData(ShopConstants.IS_PLACE_ORDER);
        String showWechatPayment =systemConfigService.getData(ShopConstants.SHOW_WECHAT_PAYMENT);
        String showIntegralPayment =systemConfigService.getData(ShopConstants.SHOW_INTEGRAL_PAYMENT);
        String extractRate =systemConfigService.getData(ShopConstants.EXTRACT_RATE);
        String disableLiveStr =systemConfigService.getData(ShopConstants.DISABLELIVE);
        List<String> disableLive = Arrays.asList(disableLiveStr.split(","));
        map.put("indexTopImages",indexTopImages);
        map.put("userTopImages",userTopImages);
        map.put("userOrderUnpaidImg",userOrderUnpaidImg);
        map.put("userOrderPaidImg",userOrderPaidImg);
        map.put("userOrderShippedImg",userOrderShippedImg);
        map.put("userQrcodeImg",userQrcodeImg);
        map.put("userBottomLogo",userBottomLogo);
        map.put("forceBindMobile",forceBindMobile);
        map.put("isPlaceOrder",isPlaceOrder);
        map.put("showWechatPayment",showWechatPayment);
        map.put("showIntegralPayment",showIntegralPayment);
        map.put("extractRate",extractRate);
        map.put("disableLive",disableLive);
        return ApiResult.ok(map);
    }
}

